<?php

namespace App\Service;

use App\Model\ConfigRentModel;
use App\Model\RentCommentModel;
use App\Model\RentLikeModel;
use App\Model\RentModel;
use App\Model\RentSeeModel;
use App\Model\StaffModel;
use App\Model\UserModel;
use App\Utility\DataConversion;
use EasySwoole\Mysqli\Exception\Exception;
use Throwable;

class RentService extends BaseService
{
    /**
     * @param $uid
     * @param $type
     * @param $limit
     * @param $page
     * @return array
     * @throws Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws Throwable
     */
    public function rentList($uid, $type, $limit, $page): array
    {
        $where = ['is_deleted' => 0];
        if ($type != 0) {
            switch ($type) {
                case 1:
                    $where['rent_type'] = 7;
                    break;
                case 2:
                    $where['rent_type'] = 8;
                    break;
                case 3:
                    $where['is_anxuan'] = 1;
                    break;
                case 4:
                    $where['renovation_type'] = 56;
                    break;
            }
        }

        $model = RentModel::create();
        $model->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->order("id", "DESC")->all($where);
        $result = $model->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();

        if (empty($list)) {
            return [
                'result' => false,
                'msg' => '暂无数据'
            ];
        }

        $data = [];
        foreach ($list as $item) {
            $user = UserModel::create()->getUser(['id' => $item['uid']]);
            $item['username'] = $user->username;
            $item['phone'] = $user->phone;
            $item['avatar'] = $user->avatar;
            $item['rent_type_label'] = ConfigService::getInstance()->getRentType($item['rent_type']);
            $item['amount_type_label'] = ConfigService::getInstance()->getRentType($item['amount_type']);
            $item['house_type_label'] = ConfigService::getInstance()->getRentType($item['house_type']);
            $item['floor_type_label'] = ConfigService::getInstance()->getRentType($item['floor_type']);
            $item['arrow_type_label'] = ConfigService::getInstance()->getRentType($item['arrow_type']);
            $item['renovation_type_label'] = ConfigService::getInstance()->getRentType($item['renovation_type']);
            $equipment = ConfigRentModel::create()->where("id", json_decode($item['equipment_type'], true), "IN")->all();
            $item['equipment_type_label'] = array_column($equipment, 'label');
            $span = ConfigRentModel::create()->where("id", json_decode($item['span'], true), "IN")->all();
            $item['span_label'] = array_column($span, 'label');
            $item['time'] = date("Y-m-d", $item['create_time']);
            $item['images_'] = json_decode($item['images'], true);
            $item['location_'] = json_decode($item['location'], true);
            $data[] = $item;
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $title
     * @param $rent_type
     * @param $amount_type
     * @param $house_type
     * @param $floor_type
     * @param $arrow_type
     * @param $renovation_type
     * @param $area
     * @param $equipment_type
     * @param $span
     * @param $content
     * @param $location
     * @param $address
     * @param $price
     * @param $images
     * @return array|void
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function release($uid, $title, $rent_type, $amount_type, $house_type, $floor_type, $arrow_type, $renovation_type, $area, $equipment_type, $span, $content, $location, $address, $price, $images)
    {
        $par = [
            'uid' => $uid,
            'title' => $title,
            'rent_type' => $rent_type,
            'amount_type' => $amount_type,
            'house_type' => $house_type,
            'floor_type' => $floor_type,
            'arrow_type' => $arrow_type,
            'renovation_type' => $renovation_type,
            'area' => $area,
            'equipment_type' => json_encode($equipment_type),
            'span' => json_encode($span),
            'content' => $content,
            'location' => json_encode($location),
            'address' => $address,
            'price' => $price,
            'images' => json_encode($images)
        ];

        $res = RentModel::create()->addRent($par);
        if (!$res) {
            return [
                'result' => false,
                'msg' => '操作失败'
            ];
        }

        return [
            'result' => true,
            'msg' => '提交成功',
            'data' => 'success'
        ];
    }

    /**
     * @param $uid
     * @param $id
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function getRentDetail($uid, $id): array
    {
        $rent = RentModel::create()->getRent(['id' => $id]);
        if (!$rent) {
            return [
                'result' => false,
                'msg' => '该信息已删除'
            ];
        }
        $item = $rent->toArray();
        $user = UserModel::create()->getUser(['id' => $item['uid']]);
        $item['username'] = $user->username;
        $item['phone'] = $user->phone;
        $item['avatar'] = $user->avatar;
        $item['rent_type_label'] = ConfigService::getInstance()->getRentType($item['rent_type']);
        $item['amount_type_label'] = ConfigService::getInstance()->getRentType($item['amount_type']);
        $item['house_type_label'] = ConfigService::getInstance()->getRentType($item['house_type']);
        $item['floor_type_label'] = ConfigService::getInstance()->getRentType($item['floor_type']);
        $item['arrow_type_label'] = ConfigService::getInstance()->getRentType($item['arrow_type']);
        $item['renovation_type_label'] = ConfigService::getInstance()->getRentType($item['renovation_type']);
        $equipment = ConfigRentModel::create()->where("id", json_decode($item['equipment_type'], true), "IN")->all();
        $item['equipment_type_label'] = array_column($equipment, 'label');
        $span = ConfigRentModel::create()->where("id", json_decode($item['span'], true), "IN")->all();
        $item['span_label'] = array_column($span, 'label');
        $item['time'] = date("Y-m-d", $item['create_time']);
        $item['images_'] = json_decode($item['images'], true);
        $item['location_'] = json_decode($item['location'], true);
        if ($item['sid'] != 0) {
            $staff = StaffModel::create()->getUser(['id' => $item['sid']]);
            if ($staff) {
                $item['kefu'] = [
                    'id' => $staff->id,
                    'phone' => $staff->phone,
                    'username' => $staff->username,
                    'avatar' => $staff->avatar,
                    'nickname' => $staff->nickname
                ];
            }
        }

        if ($uid != $item['uid']) {
            $par = [
                'fuid' => $item['uid'],
                'uid' => $uid,
                'gid' => $id
            ];

            $res = RentSeeModel::create()->addDynamic($par);
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $item
        ];

    }

    /**
     * @param $uid
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function getMyRent($uid): array
    {
        $list = RentModel::create()->where(['uid' => $uid])->order("id", "DESC")->all();

        if (empty($list)) {
            return [
                'result' => false,
                'msg' => '暂无数据'
            ];
        }

        $data = [];
        foreach ($list as $item) {
            $user = UserModel::create()->getUser(['id' => $item['uid']]);
            $item['username'] = $user->username;
            $item['phone'] = $user->phone;
            $item['avatar'] = $user->avatar;
            $item['rent_type_label'] = ConfigService::getInstance()->getRentType($item['rent_type']);
            $item['amount_type_label'] = ConfigService::getInstance()->getRentType($item['amount_type']);
            $item['house_type_label'] = ConfigService::getInstance()->getRentType($item['house_type']);
            $item['floor_type_label'] = ConfigService::getInstance()->getRentType($item['floor_type']);
            $item['arrow_type_label'] = ConfigService::getInstance()->getRentType($item['arrow_type']);
            $item['renovation_type_label'] = ConfigService::getInstance()->getRentType($item['renovation_type']);
            $equipment = ConfigRentModel::create()->where("id", json_decode($item['equipment_type'], true), "IN")->all();
            $item['equipment_type_label'] = array_column($equipment, 'label');
            $span = ConfigRentModel::create()->where("id", json_decode($item['span'], true), "IN")->all();
            $item['span_label'] = array_column($span, 'label');
            $item['time'] = date("Y-m-d", $item['create_time']);
            $item['images_'] = json_decode($item['images'], true);
            $item['location_'] = json_decode($item['location'], true);
            $data[] = $item;
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $gid
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function likeRent($uid, $gid): array
    {
        $like = RentLikeModel::create()->getDynamic(['gid' => $gid, 'uid' => $uid]);
        if ($like) {
            return [
                'result' => false,
                'msg' => '已点赞,请勿重复操作'
            ];
        }

        $param = [
            'uid' => $uid,
            'gid' => $gid,
            'like' => 1
        ];

        $res = RentLikeModel::create()->addDynamic($param);

        if (!$res) {
            return [
                'result' => false,
                'msg' => '操作失败'
            ];
        }

        return [
            'result' => true,
            'msg' => '已点赞',
            'data' => $res
        ];
    }

    /**
     * @param $uid
     * @param $id
     * @param $gid
     * @param $content
     * @param $images
     * @param $star
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function commentRent($uid, $id, $gid, $content, $images, $star): array
    {
        $param = [
            'uid' => $uid,
            'gid' => $gid,
            'content' => $content,
            'images' => json_encode($images),
            'star' => $star
        ];
        if ($id != 0) {
            $comment = RentCommentModel::create()->getDynamic(['id' => $id]);
            if ($comment) {
                $param['nid'] = $id;
            }
        }

        $res = RentCommentModel::create()->addDynamic($param);
        if (!$res) {
            return [
                'result' => false,
                'msg' => '评论失败'
            ];
        }
        $data = $this->getRentComment($uid, $gid);
        return [
            'result' => true,
            'msg' => '评论成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $gid
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function getRentComment($uid, $gid): array
    {
        $comments = RentCommentModel::create()->where(['gid' => $gid, 'nid' => 0, 'is_deleted' => 0])->all();
        if (empty($comments)) {
            return [
                'result' => false,
                'msg' => '暂无评论'
            ];
        }
        $data = [];
        foreach ($comments as $comment) {
            $user = UserModel::create()->getUser(['id' => $comment['uid']]);
            $data[] = [
                'id' => $comment['id'],
                'username' => $user->username,
                'avatar' => $user->avatar ?? '',
                'time' => DataConversion::getInstance()->timeToDate($comment['create_time']),
                'likeNum' => $comment['likeNum'],
                'content' => $comment['content'],
                'images' => json_decode($comment['images'], true),
                'star' => $comment['star'],
                'isLike' => false,
                'reply' => $this->comment_filter($comment['id']),
                'allReply' => count($this->comment_filter($comment['id']))
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => [
                'total' => count($data),
                'data' => $data
            ]
        ];
    }

    /**
     * @param $id
     * @return array
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws Throwable
     * @throws Exception
     */
    public function comment_filter($id): array
    {
        $comments = RentCommentModel::create()->all(['nid' => $id, 'is_deleted' => 0]);
        if (!is_array($comments) || empty($comments)) return [];
        $data = [];
        foreach ($comments as $comment) {
            $user = UserModel::create()->getUser(['id' => $comment['uid']]);
            $data[] = [
                'id' => $comment['id'],
                'username' => $user->username ?? '匿名用户',
                'avatar' => $user->avatar ?? '',
                'time' => DataConversion::getInstance()->timeToDate($comment['create_time']),
                'likeNum' => $comment['likeNum'],
                'content' => $comment['content'],
                'isLike' => false,
                'reply' => $this->comment_filter($comment['id']),
                'allReply' => count($this->comment_filter($comment['id']))
            ];
        }

        return $data;
    }
}